//
//  MyLevelViewController.m
//  Brand
//
//  Created by Woody Yan on 5/22/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "config.h"
#import "AFGetData.h"
#import "MyLevelViewController.h"
#import "MyLevel.h"
#import "LevelCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "WYInnerVC.h"
#import "UIView+EidanSize.h"
#import "CollectionFixedHeaderLayout.h"
#import "LevelCollectionHeadView.h"
#import "Header.h"

#define CellIdentifer        @"CellIdentifer"
#define HeadIdentifer        @"HeadIdentifer"
#define CollectionHeight     isiOS6?kScreen_Height - self.navTopView.bottom-20:kScreen_Height - self.navTopView.bottom
static NSString * BaseURL = @"http://kuiba.haomee.net/?m=Api&a=medalPage";

@interface MyLevelViewController ()

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic,strong) NSDictionary   *allObject;
@property (nonatomic,strong) NSMutableArray *allObtainPhotos;
@property (nonatomic,strong) NSMutableArray *allNotObtainPhotos;
@property (strong, nonatomic) NSMutableArray* dataArray;
@property (strong, nonatomic) NSMutableArray* titleArray;

@end

@implementation MyLevelViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    UIImage *background = [UIImage imageNamed:@"Layer.png"];
	self.view.backgroundColor = [UIColor colorWithPatternImage:background];
	
	UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	backBtn.frame = CGRectMake(0, 0, 44, 44);
	UIImage *back = [UIImage imageNamed:@"return.png"];
    [backBtn setImage:back forState:UIControlStateNormal];
	[backBtn addTarget:self action:@selector(popOut) forControlEvents:UIControlEventTouchUpInside];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
	
	UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
	title.text = @"获得纹耀";
    title.font = [UIFont systemFontOfSize:18];
    title.backgroundColor = [UIColor clearColor];
	title.textColor = ColorWithHex(0XFFFFFF);
	title.textAlignment = NSTextAlignmentCenter;
	
	UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	navBar.backgroundColor = [UIColor clearColor];
	
	[navBar addSubview:backBtn];
	[navBar addSubview:title];
    [self drawNavTopContentView:navBar];

    
    self.allObtainPhotos = [NSMutableArray array];
    self.allNotObtainPhotos = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    //UICollectionView
 
   
    
    
    
    
    CGRect frame = CGRectMake(0, self.navTopView.bottom, kScreen_Width, CollectionHeight);
    self.collectionView = [self drawCollectionViewWithFrame:frame andFlowLayout:[self getFlowLayout]];
    [self registerCellAndHeaderForCollectionView:self.collectionView];
    
    //[self.view addSubview:self.collectionView];
    [self.view insertSubview:self.collectionView atIndex:0];
    
    NSString *str = [NSString stringWithFormat:@"&uid=%@&ak=%@",[UserObj sharedInstance].uid,[UserObj sharedInstance].accessKey];
   
    
    NSString *url = [BaseURL stringByAppendingString:str];
    [self fetchDataWithURL:url];

}

-(void) popOut
{
    [kApp hideWaitView];
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Fetch Data

- (void) fetchDataWithURL:(NSString *) requestUrl
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    [[AFGetData sharedInstance] startGet:requestUrl
                         andResultIsJSON:YES
                           andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess)
     {
         if (isSuccess) {
             
             [kApp hideWaitView];
             
             self.allObject = responseObj;
             

             [self.allObtainPhotos removeAllObjects];
             for (NSDictionary *item in [self.allObject objectForKey:@"get"]){
                 MyLevel *obj = [[MyLevel alloc] initWithType:[item objectForKey:@"type"]
                                                       picUrl:[item objectForKey:@"pic"]
                                                         name:[item objectForKey:@"name"]
                                                        reason:[item objectForKey:@"reason"]
                                                 ];
                 [self.allObtainPhotos addObject:obj];
             }
             
             [self.allNotObtainPhotos removeAllObjects];
             for (NSDictionary *item in [self.allObject objectForKey:@"notget"]){
                 MyLevel *obj = [[MyLevel alloc] initWithType:[item objectForKey:@"type"]
                                                       picUrl:[item objectForKey:@"pic"]
                                                         name:[item objectForKey:@"name"]
                                                        reason:[item objectForKey:@"reason"]
                                                  ];
                 [self.allNotObtainPhotos addObject:obj];
             }

             if([self.allObtainPhotos count])
             {
                 [self.dataArray addObject:self.allObtainPhotos];
                 [self.titleArray addObject:@"已获纹耀"];
             }
             if([self.allNotObtainPhotos count])
             {
                 [self.dataArray addObject:self.allNotObtainPhotos];
                 [self.titleArray addObject:@"未获纹耀"];
             }
             
             [self.collectionView reloadData];
             
         } else {
             [kApp hideWaitView];
             [PopTips tips:self.view Msg:NotifyNoNet];
             [self performSelector:@selector(popOut) withObject:self afterDelay:0.7];
           
         }
     }];
}

#pragma mark - UICollectionView Datasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return [self.dataArray count];
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    return [[self.dataArray objectAtIndex:section] count];

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifer forIndexPath:indexPath];
    
    MyLevel* level = [[self.dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    UIImageView* fakeImage = (UIImageView*)[cell viewWithTag:301];
    UIImageView* trueImage = (UIImageView*)[cell viewWithTag:302];
    UILabel* titleLabel = (UILabel*)[cell viewWithTag:200];
    UILabel* infoLabel = (UILabel*)[cell viewWithTag:202];
    
    if([[self.titleArray objectAtIndex:indexPath.section] isEqualToString:@"已获纹耀"])
    {
    fakeImage.image = [UIImage imageNamed:@"get_wenyao_bg.png"];
    }
    else
    {
        fakeImage.image = [UIImage imageNamed:@"not_get_wenyao_bg.png"];
    }
    
    titleLabel.text = level.type;
    infoLabel.text = level.name;
    [[AFGetData sharedInstance] initSDWebImage:level.picUrl andTrueImageView:trueImage andPlaceholderImage:nil];
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    }


#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyLevel* level = [[self.dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    WYInnerVC* innerVC = [[WYInnerVC alloc]initWithNibName:@"WYInnerVC" bundle:nil];
    innerVC.level = level;
    [self.navigationController pushViewController:innerVC animated:YES];
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    
    UICollectionReusableView *header = nil;
    
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HeadIdentifer forIndexPath:indexPath];
        UILabel *titleLabel=(UILabel *)[header viewWithTag:200];
        titleLabel.text = [self.titleArray objectAtIndex:indexPath.section];
    }
    return header;

   }

#pragma mark - UICollectionView  methods
-(UICollectionView*)drawCollectionViewWithFrame:(CGRect)frame andFlowLayout:(CollectionFixedHeaderLayout*)flowLayout
{
    UICollectionView* myCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    myCollectionView.showsVerticalScrollIndicator = NO;
    myCollectionView.showsHorizontalScrollIndicator = NO;
    myCollectionView.dataSource = self;
    myCollectionView.delegate = self;
    myCollectionView.backgroundColor = [UIColor clearColor];
    myCollectionView.clipsToBounds = NO;
    return myCollectionView;
}

-(void)registerCellAndHeaderForCollectionView:(UICollectionView*)collectionView
{
    UINib *cellNib = [UINib nibWithNibName:@"MyLevelCell" bundle:nil];
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:CellIdentifer];
    
    UINib *supplementNib = [UINib nibWithNibName:@"MyLevelHeader" bundle:nil];
    [collectionView registerNib:supplementNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeadIdentifer];
}

//一个布局管理器只能对应一个collectionView
-(CollectionFixedHeaderLayout*)getFlowLayout
{
    CollectionFixedHeaderLayout *flowLayout = [[CollectionFixedHeaderLayout alloc] init];
    flowLayout.isFiexed = NO;
    [flowLayout setItemSize:CGSizeMake(90, 140)];
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.headerReferenceSize = CGSizeMake(320, 30);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);  //top left bottom right
    return flowLayout;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
